package com.hmdp.service.impl;

import cn.hutool.db.sql.Order;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.Voucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IVoucherService;
import com.hmdp.utils.OnlyOneIDProducer;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import io.lettuce.core.models.role.RedisSlaveInstance;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.boot.autoconfigure.web.ConditionalOnEnabledResourceChain;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Transactional
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService iSeckillVoucherService;

    @Resource
    private OnlyOneIDProducer onlyOneIDProducer;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    /**
     * 用来抢购指定优惠券
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) throws InterruptedException {
        // 1.根据id从数据库中查询是否有指定优惠券
        // 由于这里是VoucherOrder类，所以不能直接借助MP来直接获得优惠券，所以要借助VoucherService类
        SeckillVoucher seckillVoucher = iSeckillVoucherService.getById(voucherId);

        if(seckillVoucher == null){
            return Result.fail("没有该种优惠券哦~");
        }

        // 2.根据当前时间判断秒杀是否开始
        LocalDateTime beginTime = seckillVoucher.getBeginTime();
//        LocalDateTime endTime = seckillVoucher.getEndTime();
        LocalDateTime now = LocalDateTime.now();
        // 2.1 如果没开始，则返回失败结果，提示不在秒杀时段
        if(now.isBefore(beginTime)){
            return Result.fail("当前不在秒杀时间段哦~");
        }
        // 3.判断库存是否充足
        Integer stock = seckillVoucher.getStock();
        // 4.如果不充足，返回失败结果，提示优惠券数量不足
        if(stock <= 0){
            return Result.fail("优惠券数量不足哦~,秒杀失败");
        }

        Long userId = UserHolder.getUser().getId();
//        SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
//        boolean isLock = lock.tryLock(1200);
        // 使用redisson创建分布式锁
        RLock lock = redissonClient.getLock("lock:order" + userId);
        boolean isLock = lock.tryLock(1L , TimeUnit.SECONDS);
        if(!isLock){
            return Result.fail("同一用户只能下一单");
        }
        try {
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
            return createVoucherOrder(voucherId);
        }finally {
            // 释放锁
            lock.unlock();
        }

    }

    @Transactional
    @Override
    public Result createVoucherOrder(Long voucherId) {
        // 5.充足的话，优惠券的库存数量减一 , 第二个eq条件是利用CAS实现乐观锁
        iSeckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id" , voucherId)
                .gt("stock" , 0)
                .update();
        // 6.记录订单信息
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setVoucherId(voucherId);
        // 6.1 获得用户信息
        UserDTO user = UserHolder.getUser();
        // 6.2 将用户信息插入
        Long userId = UserHolder.getUser().getId();
        voucherOrder.setUserId(userId);
        // 6.3 订单的id不是数据库自增的id，而是我们前面讨论的使用redis的全局唯一id，所以此处要生成
        Long orderId = onlyOneIDProducer.ProduceId("Seckill-Order");
        voucherOrder.setId(orderId);
        // 7.添加订单，返回订单id，由于订单id不是数据库生成的，而是全局唯一id生成器生成的，所以返回之前生成的id即可
        save(voucherOrder);
        return Result.ok(orderId);
    }
}
